<?php

use app\common\model\Option;
use Shopwwi\LaravelCache\Cache;
use think\Model;

function apiSuccess(string $msg = "请求成功", array|Model $data = [])
{
    $result = ['msg' => $msg, 'code' => 1, 'data' => $data];
    return json($result);
}

function apiError(string $msg = "请求失败", array $data = [])
{
    $result = ['msg' => $msg, 'code' => 0, 'data' => $data];
    return json($result);
}


/**
 * 获取系统配置
 * @return void
 */
function getOption(string $key = ""): array
{
    if (!is_string($key) || empty($key)) {
        return [];
    }
    
    $optionValue = Cache::get('em_options_' . $key);
    if (empty($data)) {
        $optionValue = Option::where('option_name', $key)->value('option_value');
        if (!empty($optionValue)) {
            Cache::put('em_options_' . $key, $optionValue);
        }
    }
    return is_string($optionValue) ? json_decode($optionValue, true) : $optionValue;
}


/**
 *
 * @param string $key 配置键值,都小写
 * @param array $data 配置值，数组
 * @param $replace 是否完全替换
 * @return bool 是否成功
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function setOption(string $key = "", array $data = [], bool $replace = false): bool
{
    if (!is_array($data) || empty($data) || !is_string($key) || empty($key)) {
        return false;
    }
    $findOption = Option::where('option_name', $key)->find();
    if ($findOption) {
        if (!$replace) {
            $oldOptionValue = $findOption['option_value'];
            if (!empty($oldOptionValue)) {
                $data = array_merge($oldOptionValue, $data);
            }
        }
        
        $option['option_value'] = json_encode($data, JSON_UNESCAPED_UNICODE);
        Option::where('option_name', $key)->update($option);
    } else {
        $option['option_name'] = $key;
        $option['option_value'] = $data;
        Option::create($option);
    }
    Cache::set('em_options_' . $key, $option);
    return true;
}


function getDomain()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return "https://" . request()->host();
    } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return "https://" . request()->host();
    }
    return "http://" . request()->host();
}

function getImageUrl($file = '')
{
    print_r($file);
    if (empty($file)) {
        return '';
    }
    if (str_starts_with($file, "http")) {
        return $file;
    }
    return getDomain() . '/upload/' . $file;
}


function getTree(array $data = [], int $parentId = 0, string $field = "parent_id"): array
{
    $result = [];
    foreach ($data as $key => $value) {
        if ($value[$field] == $parentId) {
            if ($children = getTree($data, $value['id'], $field)) {
                $value['children'] = $children;
            }
            $result[] = $value;
        }
    }
    return $result;
}

// 修改字段修改
function setFieldUpdate(\think\Model $model)
{
    $field = request()->post('field', '');
    $value = request()->post('value', '');
    $id = request()->post('id', '');
    return $model->where('id', $id)->update([$field => $value]);
}


// 如果是字符串的话转为二维数组，如果是一维数组的话转为二维数组。
function getFormatFile(array|string $images): array
{
    
    if (empty($images)) {
        return [];
    }
    
    $result = [];
    if (is_array($images)) {
        foreach ($images as $value) {
            $result[] = ['path' => $value, 'url' => getImageUrl($value), 'name' => basename($value)];
        }
    }
    if (is_string($images)) {
        $result[] = ['path' => $images, 'url' => getImageUrl($images), 'name' => basename($images)];
    }
    return $result;
}

// 设置的时候都是数组类型的，然后如果是多个的话直接返回数组，如果是一个的话直接返回第一个的字符串
function setFormatFile(array $arr = [])
{
    if (count($arr) > 1) {
        return array_map(fn($item) => $item['path'], $arr);
    }
    return !empty($arr) ? $arr[0]['path'] : '';
}

// 二维数组索引关键词搜索
function arr2Search(mixed $needle, $arr = [], $key = '')
{
    return array_search($needle, array_column($arr, $key));
}

function getParents($ruleItem, $menus)
{
    $parents = [];
    foreach ($menus as $item) {
        if (strtolower($item['path']) === strtolower($ruleItem) && !empty($item['parent_id'])) {
            $parents[] = $item['parent_id'];
            $index = arr2Search($item['parent_id'], $menus, 'id');
            // var_dump($index);
            $parents = array_merge($parents, getParents($menus[$index]['path'], $menus));
            $parents[] = $item['id'];
        }
    }
    return $parents;
}